package com.lwapp.user.interceptor;

import com.lwapp.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil=null;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查看是否是在登陆状态
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotEmpty(authorization)){
            if(StringUtils.startsWith(authorization,"Bearer ")){
                final String token =StringUtils.substring(authorization,7);
                try{
                    Claims claims = jwtUtil.parseJWT(token);
                    String  roles = (String)claims.get("roles");
                    if(StringUtils.isNotEmpty(roles)&&StringUtils.equals(roles,"admin")){
                        request.setAttribute("claims_admin",token);
                    }
                    if(StringUtils.isNotEmpty(roles)&&StringUtils.equals(roles,"user")){
                        request.setAttribute("claims_user",token);
                    }

                }catch (Exception e){
                    throw new RuntimeException("令牌不正确");
                }
            }
        }
        return true;
    }
}
